class_name OptionsScreen
extends Control


signal accept


@onready var musicVolume: RangePicker = $Background/MarginContainer/VBoxContainer/MusicVolume
@onready var soundVolume: RangePicker = $Background/MarginContainer/VBoxContainer/SoundVolume
@onready var shakeToggle: TogglePicker = $Background/MarginContainer/VBoxContainer/ShakeToggle
@onready var returnButton: LabelPicker = $Background/MarginContainer/VBoxContainer/ReturnButton


var current_selection_index: int = 0
var activables: Array[ActivableControl] = []

var input_manager: InputManager


func _ready():
	returnButton.accept.connect(accept.emit)

	activables = [musicVolume, soundVolume, shakeToggle, returnButton]
	for control: ActivableControl in activables:
		control.input_manager = input_manager

	# 初始化值
	musicVolume.set_value(OptionsManager.music_volume)
	soundVolume.set_value(OptionsManager.sound_volume)
	shakeToggle.set_value(OptionsManager.is_screen_shake_enabled)
	# 需要再设置完初始值后再绑定信号
	musicVolume.value_change.connect(on_music_volume_changed)
	soundVolume.value_change.connect(on_sound_volume_changed)
	shakeToggle.value_change.connect(on_shake_toggle_changed)

	refresh()



func _process(_delta: float):
	process_input()



func refresh():
	for i in range(0, activables.size()):
		activables[i].set_active(current_selection_index == i)



func process_input():
	var i = input_manager.up_down_input()
	if i == 0:
		return
	if i > 0:
		current_selection_index = (current_selection_index + i) % activables.size()
	elif i < 0:
		current_selection_index = (activables.size() + (current_selection_index + i)) % activables.size()
	SoundPlayer.play(SoundManager.Sound.CLICK)
	refresh()


func on_music_volume_changed(value: int):
	var db := linear_to_db(float(value) / float(musicVolume.max_value))
	OptionsManager.set_music_volume(value, db)


func on_sound_volume_changed(value: int):
	var db := linear_to_db(float(value) / float(soundVolume.max_value))
	OptionsManager.set_sound_volume(value, db)


func on_shake_toggle_changed(value: bool):
	OptionsManager.set_screen_shake_enabled(value)
